<?php
header ( "Content-type:text/html;charset=utf-8" );
class PluginManager {
	
	protected static $_listeners = array ();

	public function __construct() {
		$dirName = getcwd () . '/Plugins/';
		$dir = dir ( $dirName );
		while ( false !== ($entry = $dir->read ()) ) {
			if ($entry == '.' || $entry == '..' || $entry == ".svn") {
				continue;
			}
			$path = $dirName . DIRECTORY_SEPARATOR . $entry;
			$addonsFile = $path . DIRECTORY_SEPARATOR . $entry . 'Actions.class.php';
			$fileAddons = array ();
			$list = M('Addons')->where("status='1'")->select();
			if(empty($list)) return false;
			foreach($list as $k => $v) {
				if($v['name'] == $entry) {
					if(is_file($addonsFile)) {
						require_once $addonsFile;
						$class = $v['name'] . 'Actions';
						if(class_exists($class)) {
							new $class($this);
						}
					}
				}
			}
		}
	}
	
	/**
	 * 注册需要监听的插件方法（钩子）
	 *
	 * @param string $hook        	
	 * @param object $reference        	
	 * @param string $method        	
	 */
	static function register($hook, &$reference, $method) {
		// 获取插件要实现的方法
		$key = get_class ( $reference ) . '->' . $method;
		// 将插件的引用连同方法push进监听数组中
		self::$_listeners [$hook] [$key] = array (
				&$reference,
				$method
		);
	}
	/**
	 * 触发一个钩子
	 *
	 * @param string $hook
	 *        	钩子的名称
	 * @param mixed $data
	 *        	钩子的入参
	 * @return mixed
	 */
	static function trigger($hook, $data = '') {
		$result = '';
		// 查看要实现的钩子，是否在监听数组之中
		if (isset ( self::$_listeners [$hook] ) && is_array ( self::$_listeners [$hook] ) && count ( self::$_listeners [$hook] ) > 0) {
			// 循环调用开始
			foreach ( self::$_listeners [$hook] as $listener ) {
				// 取出插件对象的引用和方法
				$class = & $listener [0];
				$method = $listener [1];
				if (method_exists ( $class, $method )) {
					// 动态调用插件的方法
					$result .= $class->$method ( $data );
				}
			}
		}
		return $result;
	}
	
	static function adminUrl($addonsName,$name,$param='') {
		return URL('admin/Plugin/adminManagers',array('addonsName'=>$addonsName,'name'=>$name,'param'=>$param));
	}
	/**
	 * 实现异步加载的钩子的URL
	 * @param array $param 参数
	 */
	static public function createAddonUrl($name,$hooks,$param = null){
        $param['addon'] = $name;
        $param['hook'] = $hooks;
		return URL('home/Widget/addonsRequest', $param);
    }
	
	static function adminManger($addonsName,$name,$param) {
		if(!$addonsName) throw new Exception("您加载的插件不存在！");
		$path = getcwd () . '/Plugins/'.$addonsName;
		$filename = $path . DIRECTORY_SEPARATOR . $addonsName . 'Actions.class.php';
		if(is_file($filename)) {
			require_once($filename);
			$class = $addonsName . 'Actions';
			$method = new $class();
			$method->$name($param);
		}
	}
}

?>